#!/usr/bin/python
#coding=utf8

# JS 即时打包工具
# 依赖make.py的打包逻辑
# PORT 常量为服务端口

import BaseHTTPServer, make, os
from SocketServer import ThreadingMixIn
#Define begin
IP_ADD = "127.0.0.1"
PORT = 7654
CWD = os.getcwd()
#Define end


maker = make.Maker()

class Handler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        selfPath = self.path.split('?')[0]
        filePath = os.path.join(CWD, './' + selfPath)
        try:
            content = maker.unIncMark(filePath)
            content = "//Dev Server\r\n"+content
            head = 'HTTP/1.1 200\r\n'
        except Exception, info:
            head = 'HTTP/1.1 500\r\n'
            content = '<h1>Error<h2> %s' %(info)
        finally:
            self.wfile.write(head)
            self.send_header('Content-Length', len(content))
            if filePath[-3:] == "css":
                self.send_header('Content-Type', 'text/css')
            elif filePath[-2:] == "js":
                self.send_header('Content-Type', 'application/x-javascript')
            self.end_headers()
            self.wfile.write(content)

#
class Server(ThreadingMixIn, BaseHTTPServer.HTTPServer):
    pass

if __name__ == "__main__":
    server = Server((IP_ADD, PORT), Handler)
    print "Port: %s" % (PORT) 
    server.serve_forever()
